<?php
class UserCurrent 
{
	public static $current = false;
	public $data = false;		
	/**
	 *	Hàm khởi tạo 
	 */
	public function __construct($user = false) {
		UserCurrent::$current = &$this;   
		if(!$user){	
            if (isset($_SESSION[NAME_SESSION_USER]) AND $_SESSION[NAME_SESSION_USER]['id']>0) 
            {
				$user = $_SESSION[NAME_SESSION_USER]; 								
                UserCurrent::$current->data = $user;                    
				self::registerSession (NAME_SESSION_USER, $user );
				return;
			} else {
				UserCurrent::$current->data = false;
				return;
			}
		} else {            
            UserCurrent::$current->data = $user; 
		}        
	}

	/**
	 * 	registerSession
	 *	@name: Session Name
	 *	@value: Session Value
	 */
	static function registerSession($name, $value) {		                        
        $_SESSION [$name] = $value;
		if (!$_SESSION ['session_key'] or !in_array($name,$_SESSION ['session_key']))
        $_SESSION ['session_key'][] = $name;      
	}
	/**
	 * 	clearSession
	 */
	static function clearSession() {
		if (isset ( $_SESSION ['session_key'] ))
			foreach ($_SESSION ['session_key'] as $key )
				unset ( $_SESSION [$key] );
		unset($_SESSION ['session_key']);		
	}
	/**
	 * 	isLogin
	 */
	static public function isLogin() {        
		return isset( $_SESSION [NAME_SESSION_USER]);
	}

	/**
	 * 	is Admin
	 */
	static public function isAdmin() {        
		
		//get list admin user
		$userData = file_get_contents(ADMIN_FILE);
		$userData = explode(',', $userData);
		$userInfo = UserCurrent::$current->data;
		
		if ((array_search($userInfo ['user_name'], $userData) === 0) || (array_search($userInfo ['user_name'], $userData))) {
			return true;
		}
		
		return false;
	}
	
    /**
    * @todo: ham kiem tra login hay chua, neu chua login redirect toi trang login
    */
    static public function checkLogin()
    {
        if(!self::isLogin())
        {
            $url = Url::buildUrl(false,'home');
            Url::redirectUrl(false,$url);
        }
    }
	/**
	 *	logIn
	 *	@user
	 */
	static public function logIn($user) {		
        UserCurrent::registerSession (NAME_SESSION_USER, $user);
		UserCurrent::$current = new UserCurrent($user);
	}
	
	/**
	 *	logOut
	 */
	static public function logOut() {
		self::clearSession ();
	}	 		
}
UserCurrent::$current = new UserCurrent();
?>